package com.zjq.authoritysystem.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zjq.authoritysystem.config.redis.Cache;
import com.zjq.authoritysystem.entity.User;
import com.zjq.authoritysystem.utils.JwtUtil;
import com.zjq.authoritysystem.vo.LoginResultVo;
import com.zjq.authoritysystem.vo.result.Result;
import com.zjq.authoritysystem.vo.result.ResultCode;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Kimiaaaaa
 * @className LoginSuccessHandler
 * @Description 登录认证成功处理器类
 * @date 2023-09-19 15:04
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private Cache cache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        log.info("-----------登录认证成功处理器开始");
        response.setContentType("application/json;charset=UTF-8");

        log.info("身份验证对象主体信息：" + JSON.toJSONString(authentication.getPrincipal()));

        // authentication.getPrincipal():返回身份验证对象的主体，通常是表示当前已认证用户的对象。
        User user = JSON.parseObject(JSON.toJSONString(authentication.getPrincipal()), User.class);

        // 生成token
        String token = jwtUtil.generateToken(user);

        // 设置token的签名密钥和过期时间
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtil.getSignatureKey())   // 设置密钥
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();   //设置过期时间

        //保存token信息
        String redisTokenKey = "token_" + token;
        cache.put(redisTokenKey, token, jwtUtil.getExpire() / 1000);

        //创建LoginResultVo结果对象
        LoginResultVo loginResultVo = new LoginResultVo(user.getId(), token, expireTime);
        Result result = new Result();
        result.setData(loginResultVo);
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg("success");
        // SerializerFeature.DisableCircularReferenceDetect 消除循环引用
        String loginResult = JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
        log.info("转换成User对象：" + loginResult);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(loginResult.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();

        log.info("-----------登录认证成功处理器结束");
    }
}
